import { getAllSetting, getSetting, setSetting, type ApplianceSetting } from "@/api/appliance"
import { DISHWASHER_DRYINGASSISTANT_PROGRAMS, DISHWASHER_SETTING_DRYINGASSISTANT } from "@/constants/Command"
import { useApplianceStore } from "@/store/appliance"
import { showLoading } from "@/utils/mpHelper"

export const options: Array<{ title: string, desc: string, value: DISHWASHER_DRYINGASSISTANT_PROGRAMS }> = [
  { title: '关闭', desc: '您启动程序时，将不会为您默认选择智能烘干参数', value: DISHWASHER_DRYINGASSISTANT_PROGRAMS.OFF },
  { title: '所有程序', desc: '将在您启动程序时为您默认选择智能烘干参数', value: DISHWASHER_DRYINGASSISTANT_PROGRAMS.ALL_PROGRAM },
  { title: '节能洗', desc: '仅在您启动节能洗程序时为您默认选择智能烘干参数', value: DISHWASHER_DRYINGASSISTANT_PROGRAMS.ECO_AS_DEFAULT },
]

export function useSmartDrying() {
  const applianceStore = useApplianceStore()
  const currentAppliance = computed(() => applianceStore.current)
  const currentHaId = computed(() => currentAppliance.value?.haId || '')
  const settings = ref<ApplianceSetting[]>([])
  const optionVisible = computed(() => {
    return currentAppliance.value?.type === 'Dishwasher' && settings.value.some(setting => setting.key === DISHWASHER_SETTING_DRYINGASSISTANT)
  })

  /**
   * 智能烘干
   */
  const status = ref<DISHWASHER_DRYINGASSISTANT_PROGRAMS | null>(null)
  const statusText = ref('')

  function setAllSettings(allSettings: ApplianceSetting[]) {
    settings.value = allSettings
    nextTick(() => {
      if (!optionVisible.value) return
      loadSetting()
    })
  }
  async function loadAllSetting() {
    const res = await getAllSetting(currentHaId.value)
    setAllSettings(res.data.settings)
  }
  async function loadSetting() {
    const res = await getSetting(currentHaId.value, DISHWASHER_SETTING_DRYINGASSISTANT)
    const { value } = res.data

    status.value = value as DISHWASHER_DRYINGASSISTANT_PROGRAMS
    statusText.value = options.find(option => option.value === value)?.title || ''

    // if (!res.data.constraints) return
    // options.value = constraints.allowedvalues.map((allowedvalue, index) => ({
    //   label: constraints.displayvalues[index],
    //   value: allowedvalue
    // })) || []
  }

  /**
   * 弹框
   */
  const modalVisible = ref(false)
  function openModal() {
    modalVisible.value = true
  }
  async function onModalConfirm(value: DISHWASHER_DRYINGASSISTANT_PROGRAMS, onComplete: () => void) {
    try {
      await showLoading(async () => {
        await setSetting(currentHaId.value, DISHWASHER_SETTING_DRYINGASSISTANT, value)
        await loadSetting()
      })
    } catch (e) {
      console.error(e)
    } finally {
      onComplete()
    }
  }

  return {
    /**
     * 智能烘干选项
     */
    optionVisible,
    status,
    statusText,
    // 初始化
    loadAllSetting,
    setAllSettings,
    /**
     * 弹框
     */
    modalVisible,
    openModal,
    onModalConfirm,
  }
}